package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.mapper.DepartmentMapper;
import com.yupi.springbootinit.mapper.WorkflowTaskMapper;
import com.yupi.springbootinit.model.dto.qa.QualityInspectionRequest;
import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.entity.WorkflowTask;
import com.yupi.springbootinit.model.vo.qa.QualityInspectionDetailVO;
import com.yupi.springbootinit.service.QualityInspectionService;
import com.yupi.springbootinit.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 品质检验接口
 */
@RestController
@RequestMapping("/qa")
@Slf4j
public class QaController {

    @Resource
    private QualityInspectionService qualityInspectionService;

    @Resource
    private UserService userService;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private WorkflowTaskMapper workflowTaskMapper;

    /**
     * 获取质检任务详情
     */
    @GetMapping("/inspection/{taskId}/detail")
    @Operation(summary = "获取质检任务详情")
    @Parameter(name = "taskId", description = "任务ID", required = true, schema = @Schema(type = "string"))
    public BaseResponse<QualityInspectionDetailVO> getInspectionDetail(
            @PathVariable String taskId,
            HttpServletRequest request) {

        Long taskIdLong;
        try {
            taskIdLong = Long.parseLong(taskId);
        } catch (NumberFormatException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID格式不正确");
        }

        ThrowUtils.throwIf(taskIdLong <= 0, ErrorCode.PARAMS_ERROR, "任务ID不合法");

        User loginUser = userService.getLoginUser(request);
        checkQualityDepartment(loginUser);

        QualityInspectionDetailVO detail;
        try {
            detail = qualityInspectionService.getInspectionDetail(taskIdLong, loginUser.getId());
        } catch (BusinessException e) {
            // 处理前端精度丢失问题
            if (e.getCode() == ErrorCode.NOT_FOUND_ERROR.getCode()) {
                log.warn("精确查询失败，尝试模糊查询处理精度丢失: requestId={}", taskIdLong);

                // 在 ±20 范围内查找质检任务
                LambdaQueryWrapper<WorkflowTask> qw = new LambdaQueryWrapper<>();
                qw.between(WorkflowTask::getId, taskIdLong - 20, taskIdLong + 20)
                        .eq(WorkflowTask::getTaskType, "QUALITY_INSPECTION")
                        .eq(WorkflowTask::getIsDelete, 0)
                        .orderByAsc(WorkflowTask::getId)
                        .last("LIMIT 1");

                WorkflowTask task = workflowTaskMapper.selectOne(qw);
                if (task == null) {
                    log.error("模糊查询也失败: requestId={}", taskIdLong);
                    throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,
                            "任务不存在。请刷新任务列表后重试，或联系管理员。");
                }

                log.info("✅ 模糊查询成功: requestId={}, actualId={}, diff={}",
                        taskIdLong, task.getId(), Math.abs(taskIdLong - task.getId()));

                detail = qualityInspectionService.getInspectionDetail(task.getId(), loginUser.getId());
            } else {
                throw e;
            }
        }

        return ResultUtils.success(detail);
    }
    /**
     * 工序检验通过
     */
    @PostMapping("/steps/pass")
    public BaseResponse<Boolean> qcPass(@RequestBody QualityInspectionRequest request,
                                        HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getBatchStepId() == null, ErrorCode.PARAMS_ERROR, "batchStepId 不能为空");

        User loginUser = userService.getLoginUser(httpRequest);
        checkQualityDepartment(loginUser);

        boolean ok = qualityInspectionService.qcPass(request, loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    /**
     * 工序检验不通过
     */
    @PostMapping("/steps/fail")
    public BaseResponse<Boolean> qcFail(@RequestBody QualityInspectionRequest request,
                                        HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getBatchStepId() == null, ErrorCode.PARAMS_ERROR, "batchStepId 不能为空");

        User loginUser = userService.getLoginUser(httpRequest);
        checkQualityDepartment(loginUser);

        boolean ok = qualityInspectionService.qcFail(request, loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    /**
     * 检查用户是否属于品质部
     *
     * @param user 当前登录用户
     * @throws BusinessException 如果用户不属于品质部
     */
    private void checkQualityDepartment(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        if (user.getDepartmentId() == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户未分配部门，请联系管理员");
        }

        Department department = departmentMapper.selectById(user.getDepartmentId());
        if (department == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "部门信息不存在，请联系管理员");
        }

        // 检查部门编码是否为品质部（PZ001）
        String deptCode = department.getDepartmentCode();
        if (!"PZ001".equals(deptCode)) {
            log.warn("非品质部用户尝试访问质检接口: userId={}, userName={}, deptCode={}",
                    user.getId(), user.getUserName(), deptCode);
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,
                    "仅品质部人员可以执行质检操作（当前部门：" + department.getDepartmentName() + "）");
        }

        log.debug("品质部权限验证通过: userId={}, userName={}, deptCode={}",
                user.getId(), user.getUserName(), deptCode);
    }
}